package com.dyzx.hbb.common.exception;



import com.dyzx.hbb.common.base.Result;
import org.springframework.web.bind.MethodArgumentNotValidException;

import org.springframework.web.bind.MissingServletRequestParameterException;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.Objects;

@RestControllerAdvice
public class AppErrorExceptionAdvice {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handle(MethodArgumentNotValidException e) {
        return Result.error(400, Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public Result<String> handleRuntimeException(RuntimeException e) {
        // 过滤掉SQL异常信息中的敏感细节
        String message = e.getMessage();
        if (message != null && message.contains("SQLException")) {
            message = "数据库操作异常：" + message;
        }
        return Result.error(500, message);
    }

    @ExceptionHandler(SQLException.class)
    public Result<String> handleSQLException(SQLException e) {
        // 简化SQL异常信息，避免暴露数据库细节
        return Result.error(500, "数据库操作异常"+e.getMessage());
    }

    @ExceptionHandler(io.jsonwebtoken.ExpiredJwtException.class)
    public Result<String> handleExpiredJwtException(io.jsonwebtoken.ExpiredJwtException e) {
        return Result.error(401, "Token已过期");
    }


    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        return Result.error(400, "缺少必要参数: " + e.getParameterName());
    }

}
